package com.tecode.gmail.user.service;

import com.tecode.gmail.bean.User;
import com.tecode.gmail.user.dao.UserDao;
import com.tecode.gmail.user.util.SMSUtil;
import org.apache.commons.collections.map.HashedMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.Map;

/**
 * Created with Intellij IDEA.
 *
 * @Author: Gabriel
 * @Date: 2019-01-03
 * @Description:
 */
@Service
public class UserService {
	@Autowired
	private SMSUtil smsUtil;

	@Autowired
	private UserDao userDao;

	/**
	 * @Author Gabriel
	 * @Description //TODO
	 * @Date 2019/1/3
	 * @Param 
	 * @Return
	 * 发送短信验证码
	 */

	@Transactional
	public Map<String,Object> sendSMS(String phone){
		Map<String,Object> map = new HashedMap();
		//验证输入的手机号码是否在系统中存在。
		if(userDao.getUserByPhone(phone) == null){
			map.put("result",false);
			map.put("msg","手机号码不存在");
			return map;
		}


		map= smsUtil.sendSMS(phone);
		if(Boolean.parseBoolean(map.get("result").toString())){
			userDao.setUserVerificationCode(phone,map.get("code").toString());
		}



		return map;
	}

	/**
	 * @Author Gabriel
	 * @Description //TODO 手机验证码登录
	 * @Date 2019/1/3
	 * @Param 
	 * @Return
	 * 手机验证码登录
	 */

	@Transactional
	public Map<String,Object> login(User user) {
		Map<String,Object> map = new HashedMap();
		map.put("result", false);
		map.put("msg", "服务器内部错误，请联系管理员。");
		try {
			User queryUser = userDao.getUserByPhone(user.getPhone());

			if (queryUser == null) {
				map.put("result", false);
				map.put("msg", "手机号码不存在");
				return map;
			}

			if (!(queryUser.getVerificationCode().equals(user.getVerificationCode()))) {
				map.put("result", false);
				map.put("msg", "验证码错误");
				return map;
			}
			if (new Date().getTime() > queryUser.getLastTime().getTime()) {
				map.put("result", false);
				map.put("msg", "验证码过期");
				return map;
			}

			map.put("result", true);
			map.put("msg", "登录成功");

			map.put("loginUser",queryUser);
			//让验证码时效。
			userDao.setUserVerificationCode(user.getPhone(), "-1");
			return map;
		}catch (Exception e){
			return  map;
		}
	}
}